﻿using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;

namespace Songhay.Tests
{
    /// <summary>
    /// Summary description for FrameworkTest
    /// </summary>
    [TestClass]
    public class FrameworkTest
    {
        [TestInitialize]
        public void ClearPreviousTestResults()
        {
            var directory = Directory.GetParent(TestContext.TestDir);

            directory.GetFiles()
                .OrderByDescending(f => f.LastAccessTime).Skip(1)
                .ToList().ForEach(f => f.Delete());

            directory.GetDirectories()
                .OrderByDescending(d => d.LastAccessTime).Skip(1)
                .ToList().ForEach(d => d.Delete(true));
        }

        /// <summary>
        ///Gets or sets the test context which provides
        ///information about and functionality for the current test run.
        ///</summary>
        public TestContext TestContext { get; set; }

        [TestMethod]
        public void ShouldInvokeSingletonMethodWithReflection()
        {
            var type = Type.GetType("Songhay.Tests.Singleton");
            MethodInfo method = type.GetMethod("AddNumbers");
            PropertyInfo prop = type.GetProperty("Instance",
                BindingFlags.Static | BindingFlags.Public);

            var instance = prop.GetValue(prop, Type.EmptyTypes);
            var result = (int)method.Invoke(instance, Type.EmptyTypes);

            Assert.AreEqual(11, result);
        }
    }

    public sealed class Singleton
    {
        private static readonly Singleton instance = new Singleton();

        private Singleton() { }

        public static Singleton Instance
        {
            get
            {
                return instance;
            }
        }

        public int AddNumbers()
        {
            return 10 + 1;
        }
    }
}
